package com.sduept.nwld.dataserver.manager.cim;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Set;

import javax.interceptor.Interceptors;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.sduept.bigdata.special.maintenance.model.MaintenanceStation;
import com.sduept.cim.model.controlarea.HostControlArea;
import com.sduept.cim.model.core.BaseVoltage;
import com.sduept.cim.model.core.ConnectivityNode;
import com.sduept.cim.model.core.SubControlArea;
import com.sduept.cim.model.core.Substation;
import com.sduept.cim.model.core.VoltageLevel;
import com.sduept.cim.model.extend.LineSegment;
import com.sduept.cim.model.generation.GeneratingUnit;
import com.sduept.cim.model.generation.HydroGeneratingUnit;
import com.sduept.cim.model.generation.ThermalGeneratingUnit;
import com.sduept.cim.model.history.extend.LineSegmentHistory;
import com.sduept.cim.model.history.wires.ACLineSegmentHistory;
import com.sduept.cim.model.history.wires.DcLinesegmentHistory;
import com.sduept.cim.model.protection.ProtectionEquipment;
import com.sduept.cim.model.wires.ACLineSegment;
import com.sduept.cim.model.wires.Breaker;
import com.sduept.cim.model.wires.BusbarSection;
import com.sduept.cim.model.wires.Compensator;
import com.sduept.cim.model.wires.DCSwitch;
import com.sduept.cim.model.wires.DcLinesegment;
import com.sduept.cim.model.wires.Disconnector;
import com.sduept.cim.model.wires.EnergyConsumer;
import com.sduept.cim.model.wires.Ground;
import com.sduept.cim.model.wires.GroundDisconnector;
import com.sduept.cim.model.wires.PowerTransformer;
import com.sduept.cim.model.wires.SynchronousMachine;
import com.sduept.cim.model.wires.TransformerWinding;
import com.sduept.cim.query.service.GenBreakerRelation;
import com.sduept.core.dao.SuperDAO;
import com.sduept.nwld.dataserver.interceptors.CimModeCreateOrUpdatelInterceptor;
import com.sduept.nwld.dataserver.interceptors.CimModeDeleteInterceptor;
import com.sduept.nwld.dataserver.util.CimUtils;
import com.sduept.stardfile.parser.model.scd.Bay;

@Service
public class CimManager {
    @Autowired
    private SuperDAO dao;

    @Autowired
    private GenBreakerRelation relation;

    /**
     * 根据站的id获取站
     *
     * @param name
     * @return
     */
    public Substation getStationById(String id) {
        return dao.findById(id, Substation.class);
    }

    public List<Substation> getStationByIds(String[] ids) {
        return dao.findByConditionIN("id", ids, Substation.class);
    }

    /**
     * 根据站的name获取站
     *
     * @param name
     * @return
     */
    public List<Substation> getStationByName(String name) {
        return dao.findByCondition(Substation.class, "name=? and standVoltagelevel > 0", name);
    }

    public String getSingelStationIdByName(String name) {
        List<Substation> list = dao.findByCondition(Substation.class, "standVoltagelevel> 499 and name = ? ", name);
        if (list != null && list.size() > 0) {
            return list.get(0).getId();
        } else {
            return null;
        }
    }

    /**
     * 查询某个范围电压等级的变电站
     *
     * @param startvoltageLevel
     * @param endVoltageLevel
     * @return
     */
    public List<Substation> listStationsByVoltageLevel(Integer startvoltageLevel, Integer endVoltageLevel) {
        String sql = "1=1 ";
        if (startvoltageLevel != null) {
            sql = sql + " and standVoltagelevel > " + (startvoltageLevel - 1);
        }
        if (endVoltageLevel != null) {
            sql = sql + " and standVoltagelevel < " + (endVoltageLevel + 1);
        }
        if (StringUtils.isEmpty(sql)) {
            return getAllStations();
        } else {
            return dao.findByCondition(Substation.class, sql);
        }

    }

    public List<Substation> listStationsByVoltage(float standVoltagelevel) {
        return dao.findByCondition(Substation.class, "standVoltagelevel=?", standVoltagelevel);
    }

    /**
     * 获取所有ACLineSegment
     *
     * @return
     */
    public List<ACLineSegment> findAllAcLineSegement() {
//		return dao.findByCondition(ACLineSegment.class, "status=?", 0);
        return dao.findAll(ACLineSegment.class);
    }

    /**
     * 查找可用和不可用的AclineSegment
     *
     * @return
     */
    public List<ACLineSegment> findUsedAndUnUsedAclineSegment() {
        return dao.findAll(ACLineSegment.class);
    }

    public List<Substation> findUsedAndUnUsedStations() {
        return dao.findAll(Substation.class);
    }

    public List<Breaker> findUsedAndUnUsedBreakers() {
        return dao.findAll(Breaker.class);
    }

    public List<BusbarSection> findUsedAndUnUsedBusBars() {
        return dao.findAll(BusbarSection.class);
    }

    public List<Compensator> findUsedAndUnUsedCompens() {
        return dao.findAll(Compensator.class);
    }

    public List<DcLinesegment> findUsedAndUnUsedDclines() {
        return dao.findAll(DcLinesegment.class);
    }

    public List<PowerTransformer> findUsedAndUnUsedPowerTransformer() {
        return dao.findAll(PowerTransformer.class);
    }

    /**
     * 获取所有的断路器
     */
    public List<Breaker> findAllBreaker() {
//		return dao.findByCondition(Breaker.class, "status=?", 0);
        return dao.findAll(Breaker.class);
    }

    public List<DcLinesegment> findAllDclineSegement() {
//		return dao.findByCondition(DcLinesegment.class, "status=?", 0);
        return dao.findAll(DcLinesegment.class);
    }

    /**
     * 获取Acline中的所有标准电压等级
     */
    @SuppressWarnings("unchecked")
    public List<Float> findAclineStandVolLevels() {
        return (List<Float>) dao.nativeQuery(
                "select standVoltagelevel from t_cim_aclinesegment  group by standVoltagelevel order by standVoltagelevel");
    }

    /**
     * 获取Acline中的所有标准电压等级，返回List<String>
     */
    @SuppressWarnings("unchecked")
    public List<String> findAclineStandVolLevelsStr() {
        return (List<String>) dao.nativeQuery(
                "select standVoltagelevel from t_cim_aclinesegment  group by standVoltagelevel order by standVoltagelevel");
    }

    @SuppressWarnings("unchecked")
    public List<Float> findStationStandVolLevels() {
        return (List<Float>) dao.nativeQuery(
                "select standVoltagelevel from t_cim_substation  group by standVoltagelevel order by standVoltagelevel");
    }

    @SuppressWarnings("unchecked")
    public List<Float> findBusBarStandVolLevels() {
        return (List<Float>) dao.nativeQuery(
                "select standVoltagelevel from t_cim_busbarsection  group by standVoltagelevel order by standVoltagelevel");
    }

    /**
     * 根据id 获取线路
     *
     * @param id
     * @return
     */
    public ACLineSegment getAcLineSegmentById(String id) {
        if (StringUtils.isEmpty(id)) {
            return null;
        }
        return dao.findById(id, ACLineSegment.class);
    }

    public List<Substation> getStationsByAclineId(String aclineId) {
        List<Substation> list = new ArrayList<Substation>();
        ACLineSegment acLine = getAcLineSegmentById(aclineId);
        if (!StringUtils.isEmpty(acLine.getStartST()) && !StringUtils.isEmpty(acLine.getEndST())) {
            list.add(getStationById(acLine.getStartST()));
            list.add(getStationById(acLine.getEndST()));
        }
        return list;
    }

    /**
     * 获取所有母线
     */
    public List<BusbarSection> findAllBusBarSection() {
//		return dao.findByCondition(BusbarSection.class, "status=0");
        return dao.findAll(BusbarSection.class);
    }

    /**
     * 通过变电站Id 获取交流线段
     *
     * @param stationId
     * @return
     */
    public List<ACLineSegment> getAcLineSegmentsBySubstation(String stationId) {
        return dao.findByCondition(ACLineSegment.class, "startST=? or endST=?  ", stationId, stationId);
    }

    /**
     * 通过变电站Id，标准电压等级 获取交流线段
     *
     * @param stationId
     * @param standVoltagelevel
     * @return
     */
    public List<ACLineSegment> getAcLineSegmentsBySubstationIdAndStandVoltagelevel(String stationId,
                                                                                   float standVoltagelevel) {
        return dao.findByCondition(ACLineSegment.class, "( startST=? or endST=?) and standVoltagelevel>=?", stationId,
                stationId, standVoltagelevel);
    }

    public List<ACLineSegment> getAcLineSegmentsByStandVoltagelevel(float standVoltagelevel) {
        return dao.findByCondition(ACLineSegment.class, "standVoltagelevel = ?", standVoltagelevel);
    }

    /**
     * 获取区间范围内的线路[开始，结束]
     *
     * @param startVoltagelevel
     * @param endVoltagelevel
     * @return
     */
    public List<ACLineSegment> getAcLineSegments(Float startVoltagelevel, Float endVoltagelevel) {
        String sql = "1=1 ";
        if (startVoltagelevel != null) {
            sql = sql + " and standVoltagelevel >=" + startVoltagelevel;
        }
        if (endVoltagelevel != null) {
            sql = sql + " and standVoltagelevel <=" + endVoltagelevel;
        }
        return dao.findByCondition(ACLineSegment.class, sql);
    }

    /**
     * 根据名称获取所有ACLineSegment
     *
     * @param name
     * @return
     */
    public List<ACLineSegment> getAcLineSegmentsByName(String name) {
        return dao.findByCondition(ACLineSegment.class, "name=?", name);
    }

    /**
     * 根据名称获取所有DcLinesegment
     *
     * @param name
     * @return
     */
    public List<DcLinesegment> getDcLineSegmentsByName(String name) {
        return dao.findByCondition(DcLinesegment.class, "name=?", name);
    }

    public List<Float> listAllAcLineVoltage() {
        List<ACLineSegment> voltages = dao.findByCondition(ACLineSegment.class,
                "1=1 group by standVoltagelevel order by standVoltagelevel desc");
        List<Float> result = new ArrayList<>();
        for (ACLineSegment v : voltages) {
            result.add(v.getStandVoltagelevel());
        }
        return result;
    }

    /**
     * 根据电压等级统计线路
     *
     * @param standVoltagelevel
     * @return
     */
    public long countACLineByCondition(float standVoltagelevel) {

        Object[] whereArgs = new Object[1];
        whereArgs[0] = standVoltagelevel;
        long sum = dao.count("standVoltagelevel = ? ", whereArgs, ACLineSegment.class);
        return sum;
    }

    /**
     * 通过变电站Id 获取保护设备
     *
     * @param stationId
     * @return
     */
    public List<ProtectionEquipment> getProtectionEquipmentsByStationId(String stationId) {
        return dao.findByCondition(ProtectionEquipment.class, "subId=?", stationId);
    }

    public List<ProtectionEquipment> getProtectionEquipmentsByStationIdAndStandVoltage(String stationId, float vol) {
        return dao.findByCondition(ProtectionEquipment.class, "subId=? and standvoltage >?",
                stationId, vol);
    }

    /**
     * 根据一次设备id，厂站id获取该一次设备关联断路器的断路器保护
     *
     * @param stationId
     * @param primaryEquId
     * @return
     */
    public List<ProtectionEquipment> getBreakerProtectByPrimaryIdAndStationId(String primaryEquId, String stationId) {
        List<Breaker> list = getBreakersById(primaryEquId, stationId);
        List<String> protectedId = new ArrayList<>();
        for (Breaker b : list) {
            protectedId.add(b.getId());
        }
        return getProtectionEquipmentsByprotectedIds(protectedId.toArray(new String[0]));
    }

    /**
     * 获得一次设备的断路器保护，如果是线路会获取两端的断路器保护
     *
     * @param primaryEquId
     * @return
     */
    public List<ProtectionEquipment> getBreakerProtectByPrimaryId(String primaryEquId) {
        List<Breaker> list = getBreakersById(primaryEquId);
        List<String> protectedId = new ArrayList<>();
        for (Breaker b : list) {
            protectedId.add(b.getId());
        }
        return getProtectionEquipmentsByprotectedIds(protectedId.toArray(new String[0]));
    }

    /**
     * 根据变电站id集合获取保护设备
     *
     * @param id
     * @return
     */
    public List<ProtectionEquipment> getMainProtectionEquipmentsByStationId(String stationId) {
        return dao.findByCondition(ProtectionEquipment.class, "subId=? and type like '%主%'",
                stationId);
    }

    /**
     * 根据变电站集合获取保护设备
     *
     * @param ids
     * @return
     */
    public List<ProtectionEquipment> getProtectionEquipmentsByStationId(String[] ids) {
        return dao.findByConditionIN("subId", ids, ProtectionEquipment.class);
    }

    /**
     * 根据变电站集合查询主保护设备
     *
     * @param ids
     * @return
     */
    public List<ProtectionEquipment> getMainProtectionEquipmentsByStationId(String[] ids) {
        ArrayList<ProtectionEquipment> arrayList = new ArrayList<ProtectionEquipment>();
        List<ProtectionEquipment> list = dao.findByConditionIN("subId", ids,
                ProtectionEquipment.class);
        for (ProtectionEquipment equipment : list) {
            if (!StringUtils.isEmpty(equipment.getType())) {
                if (equipment.getType().contains("主")) {
                    arrayList.add(equipment);
                }
            }
        }
        return arrayList;
    }

    /**
     * 通过protectId 查询保护设备
     *
     * @param protectId
     * @return
     */
    public List<ProtectionEquipment> getProtectionEquipmentsByProtectedId(String protectId) {
        return dao.findByCondition(ProtectionEquipment.class, "protectedId=?", protectId);
    }

    /**
     * 根据线路Id获取主保护设备
     *
     * @param aclineId
     * @return
     */
    public List<ProtectionEquipment> getProtectionEquipmentsByAclineId(String aclineId) {
        ACLineSegment acLine = dao.findById(aclineId, ACLineSegment.class);
        List<ProtectionEquipment> list = dao.findByCondition(ProtectionEquipment.class,
                "protectedType=? and protectedName=? and type like '主%' ", "线路", acLine.getName());
        return list;
    }

    /**
     * 根据线路Id 变电站ID，获取主保护设备
     *
     * @param subStationId
     * @param aclineId
     * @return
     */
    public List<ProtectionEquipment> getProtectionEquipmentsByAclineId(String subStationId, String aclineId) {
        List<ProtectionEquipment> list = dao.findByCondition(ProtectionEquipment.class,
                "subId=? and protectedType=? and protectedId=? and type like '%主%' ",
                subStationId, "线路", aclineId);
        return list;
    }

    /**
     * 根据变电站集合获取主保护设备
     *
     * @param ids
     * @return
     */
    public List<ProtectionEquipment> getProtectionEquipmentsByAclineId(String[] ids) {
        ArrayList<ProtectionEquipment> list = new ArrayList<ProtectionEquipment>();
        List<ACLineSegment> aclines = dao.findByConditionIN("id", ids, ACLineSegment.class);
        for (ACLineSegment acLine : aclines) {
            List<ProtectionEquipment> condition = dao.findByCondition(ProtectionEquipment.class,
                    "protectedType=? and protectedName=? and type like ?", "线路", acLine.getName(),
                    "%主%");
            list.addAll(condition);
        }
        return list;
    }

    /**
     * 根据被保护设备的ids 获取保护设备
     *
     * @param ids
     * @return
     */
    public List<ProtectionEquipment> getProtectionEquipmentsByprotectedIds(String[] ids) {
        List<ProtectionEquipment> list = dao.findByConditionIN("protectedId", ids,
                ProtectionEquipment.class);
        return list;
    }

    /**
     * 通过变电站Id,保护设备名称 获取保护设备
     *
     * @param stationId
     * @return
     */
    public List<ProtectionEquipment> getProtectionEquipmentsByStationIdAndName(String stationId, String name) {
        return dao.findByCondition(ProtectionEquipment.class, "subId=? and name=?", stationId,
                name);
    }

    /**
     * 通过变电站Id,被保护的一次设备id名称 获取保护设备
     *
     * @param stationId
     * @return
     */
    public List<ProtectionEquipment> getProtectionByStationIdAndEid(String stationId, String name) {
        return dao.findByCondition(ProtectionEquipment.class, "subId=? and protectedId=?",
                stationId, name);
    }

    /**
     * 通过变电站Id,保护设备类型 获取保护设备
     *
     * @param stationId
     * @return
     */
    public List<ProtectionEquipment> getProtectionEquipmentsByStationIdAndType(String stationId, String type) {
        return dao.findByCondition(ProtectionEquipment.class, "subId=? and type=?", stationId,
                type);
    }

    /**
     * 通过变电站Id 获取断路器
     *
     * @param stationId
     * @return
     */
    public List<Breaker> getBreakersByStationId(String stationId) {
        return dao.findByCondition(Breaker.class, "subId=?", stationId);
    }

    /**
     * 通过变电站Id,断路器名称 获取断路器
     *
     * @param stationId
     * @return
     */
    public List<Breaker> getBreakersByStationIdAndName(String stationId, String name) {
        return dao.findByCondition(Breaker.class, "subId=? and name=?", stationId, name);
    }

    /**
     * 通过变电站Id,电压等级Id 获取断路器
     *
     * @param stationId
     * @param volId
     * @return
     */
    public List<Breaker> getBreakersByStationIdAndVoltagelevel(String stationId, float standVoltagelevel) {
        return dao.findByCondition(Breaker.class, "subId=? and standVoltagelevel>?", stationId, standVoltagelevel - 1);
    }

    /**
     * 通过变电站Id 获取母线
     *
     * @param stationId
     * @return
     */
    public List<BusbarSection> getBusbarSectionsByStationId(String stationId) {
        return dao.findByCondition(BusbarSection.class, "subId=?", stationId);
    }

    /**
     * 通过变电站Id母线名称 获取母线
     *
     * @param stationId
     * @return
     */
    public List<BusbarSection> getBusbarSectionsByStationIdAndName(String stationId, String name) {
        return dao.findByCondition(BusbarSection.class, "subId=? and name=?", stationId, name);
    }

    /**
     * @param stationId
     * @param standVoltagelevel
     * @return
     */
    public List<BusbarSection> getBusbarSectionsByStationIdAndStandVoltagelevel(String stationId,
                                                                                float standVoltagelevel) {
        return dao.findByCondition(BusbarSection.class, "subId=? and standVoltagelevel>?", stationId,
                standVoltagelevel);
    }

    /**
     * @param standVoltagelevel
     * @return
     */
    public List<BusbarSection> getBusbarSectionsByStandVoltagelevel(float standVoltagelevel) {
        return dao.findByCondition(BusbarSection.class, " standVoltagelevel>=?", standVoltagelevel);
    }

    /**
     * 通过变电站Id 获取变压器
     *
     * @param stationId
     * @return
     */
    public List<PowerTransformer> getPowerTransformersByStationId(String stationId) {
        return dao.findByCondition(PowerTransformer.class, "subId=?", stationId);
    }

    /**
     * 通过变电站Id 获取变压器绕组
     *
     * @param stationId
     * @return
     */
    public List<TransformerWinding> getTransformerWindingsByStationId(String stationId) {
        return dao.findByCondition(TransformerWinding.class, "subId=?", stationId);
    }

    /**
     * 通过变电站Id变压器名称 获取变压器
     *
     * @param stationId
     * @return
     */
    public List<PowerTransformer> getPowerTransformersByStationIdAndName(String stationId, String name) {
        return dao.findByCondition(PowerTransformer.class, "subId=? and name=?", stationId, name);
    }

    /**
     * 根据id获取断路器
     *
     * @param id
     * @return
     */
    public Breaker getBreakerByBreakerId(String id) {
        return dao.findById(id, Breaker.class);
    }

    /**
     * 根据电压等级获取断路器
     *
     * @param id
     * @return
     */
    public List<Breaker> getBreakerByStandVoltagelevel(float standVoltagelevel) {
        return dao.findByCondition(Breaker.class, "standVoltagelevel>?", standVoltagelevel - 1);
    }

    /**
     * 根据设备Id,找到对应的rdfId
     *
     * @param id
     * @return
     */
    private List<String> getRdfIdById(String id) {
        List<String> rtn = new ArrayList<String>();
        ACLineSegment acLineSegment = getAcLineSegmentById(id);
        if (null != acLineSegment) {
            rtn.add(acLineSegment.getRdfId());
            return rtn;
        }
        BusbarSection bus = getBusbarSectionsById(id);
        if (null != bus) {
            rtn.add(bus.getRdfId());
            return rtn;
        }
        TransformerWinding winding = getTransformerWindingById(id);
        if (null != winding) {
            rtn.add(winding.getRdfId());
            return rtn;
        }
        PowerTransformer power = getPowerTransformersById(id);
        if (null != power && StringUtils.isNotEmpty(power.getRdfId())) {
            List<TransformerWinding> list = getTransformerWindingsBypowerTransformerRdfId(power.getRdfId());
            for (TransformerWinding w : list) {
                rtn.add(w.getRdfId());
            }
            return rtn;
        }
        return rtn;
    }

    public Breaker getBreakerByRdfId(String rdfId) {
        List<Breaker> list = dao.findByCondition(Breaker.class, "rdfId=?", rdfId);
        if (null != list) {
            return list.get(0);
        }
        return null;
    }

    /**
     * 通过变压器绕组rdfId/母线rdfId/交流线rdfId 获取断路器 注意：若传入Id 为变压器Id, 则会查找该变压器的所有绕组关联的断路器
     *
     * @param acLineSegmentId
     * @return
     */
    public List<Breaker> getBreakersById(String id) {
        List<Breaker> rtn = new ArrayList<>();
        List<String> rdfIds = getRdfIdById(id);
        for (String rdfId : rdfIds) {
            List<Breaker> tmpList = getBreakersByRdfId(rdfId);
            rtn.addAll(tmpList);
        }
        return rtn;
    }

    private List<Breaker> getBreakersByRdfId(String rdfId) {
        List<Breaker> list = new ArrayList<>();
        if (StringUtils.isEmpty(rdfId)) {
            return list;
        }
        try {
            Set<String> breakerById = relation.getBreakerById(rdfId);
            for (String s : breakerById) {
                Breaker breaker = getBreakerByRdfId(s);
                if (breaker != null) {
                    list.add(breaker);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return list;
    }

    /**
     * 通过变压器Id/母线Id/交流线Id 获取刀闸
     *
     * @param acLineSegmentId
     * @return
     */
    public List<Disconnector> getDisconnectorById(String id) {
        List<Disconnector> list = new ArrayList<>();
        List<Breaker> breakers = getBreakersById(id);
        for (Breaker b : breakers) {
            Set<String> disconnectorIds = relation.getDisconnectorsByBreakerId(b.getRdfId());
            for (String rdfid : disconnectorIds) {
                Disconnector dis = getDisconnectorByRdfid(rdfid);
                if (dis != null) {
                    list.add(dis);
                }
            }
        }
        return list;
    }

    public Disconnector getDisconnectorByRdfid(String rdfid) {
        List<Disconnector> list = dao.findByCondition(Disconnector.class, "rdfId=?", rdfid);
        if (list.size() > 0)
            return list.get(0);
        else
            return null;
    }

    /**
     * 通过变压器绕组Id/母线Id/交流线Id 和变电站Id,获取断路器 注意：若传入Id 为变压器Id, 则会查找该变压器的所有绕组关联的断路器
     *
     * @param acLineSegmentId
     * @return
     */
    public List<Breaker> getBreakersById(String id, String stationId) {
        List<Breaker> rtn = new ArrayList<>();
        List<String> rdfIds = getRdfIdById(id);
        for (String rdfId : rdfIds) {
            rtn.addAll(getBreakersByRdfId(rdfId, stationId));
        }
        return rtn;
    }

    /**
     * 通过变压器绕组rdfId/母线rdfId/交流线rdfId 获取关联断路器
     *
     * @param rdfId
     * @param stationId
     * @return
     */
    private List<Breaker> getBreakersByRdfId(String rdfId, String stationId) {
        List<Breaker> list = new ArrayList<>();
        if (StringUtils.isEmpty(rdfId)) {
            return list;
        }
        try {
            Set<String> breakerById = relation.getBreakerById(rdfId);
            for (String s : breakerById) {
                Breaker breaker = getBreakerByRdfId(s);
                if (breaker != null) {
                    if (StringUtils.isNotEmpty(stationId) && StringUtils.isNotEmpty(breaker.getSubId())
                            && stationId.equals(breaker.getSubId())) {
                        list.add(breaker);
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return list;
    }

    /**
     * 通过变电站Id 查找电压等级
     *
     * @param stationId
     * @return
     */
    public List<VoltageLevel> getVoltagelevelsBySubStationId(String stationId) {
        return dao.findByCondition(VoltageLevel.class, "subId=?", stationId);
    }

    /**
     * 通过voltageLevelId 查找母线
     *
     * @param voltageLevelId
     * @return
     */
    public List<BusbarSection> getBusbarSectionsByVoltageLevelId(String voltageLevelId) {
        return dao.findByCondition(BusbarSection.class, "equipmentContainer=? ", voltageLevelId);
    }

    /**
     * 通过voltageLevelId 查找变压器绕组
     *
     * @param voltageLevelId
     * @return
     */
    public List<TransformerWinding> getTransformerWindingsByVoltageLevelId(String voltageLevelId) {
        return dao.findByCondition(TransformerWinding.class, "equipmentContainer=?", voltageLevelId);
    }

    /**
     * 通过voltageLevelId 查找连接节点
     *
     * @param voltageLevelId
     * @return
     */
    public List<ConnectivityNode> getConnectivityNodesByVoltageLevelId(String voltageLevelId) {
        return dao.findByCondition(ConnectivityNode.class, "equipmentContainer=?", voltageLevelId);
    }

    /**
     * 通过voltageLevelId 查找间隔
     *
     * @param voltageLevelId
     * @return
     */
    public List<Bay> getBaysByVoltageLevelId(String voltageLevelId) {
        return dao.findByCondition(Bay.class, "voltageLevel=?", voltageLevelId);
    }

    /**
     * 根据bayId 获取交流线
     *
     * @param bayId
     * @return
     */
    public List<ACLineSegment> getACLineSegmentsByBayId(String bayId) {
        return dao.findByCondition(ACLineSegment.class, "equipmentContainer=?", bayId);
    }

    /**
     * 根据bayId 获取断路器
     *
     * @param bayId
     * @return
     */
    public List<Breaker> getBreakersByBayId(String bayId) {
        return dao.findByCondition(Breaker.class, "equipmentContainer=?", bayId);
    }

    /**
     * 根据bayId 获取电抗器
     *
     * @param bayId
     * @return
     */
    public List<Compensator> getCompensatorsByBayId(String bayId) {
        return dao.findByCondition(Compensator.class, "equipmentContainer=?", bayId);
    }

    /**
     * 根据id获取电抗器
     *
     * @param id
     * @return
     */
    public Compensator getCompensatorById(String id) {
        return dao.findById(id, Compensator.class);
    }

    /**
     * 根据stationId 获取电抗器
     *
     * @param bayId
     * @return
     */
    public List<Compensator> getCompensatorsByStationId(String stationId) {
        return dao.findByCondition(Compensator.class, "subId=? ", stationId);
    }

    /**
     * 根据stationId 获取电抗器
     *
     * @param bayId
     * @return
     */
    public List<Compensator> getCompensatorsByStationIdAndName(String stationId, String name) {
        return dao.findByCondition(Compensator.class, "subId=? and name=?", stationId, name);
    }

    /**
     * 根据bayId 获取直流开关
     *
     * @param bayId
     * @return
     */
    public List<DCSwitch> getDCSwitchsByBayId(String bayId) {
        return dao.findByCondition(DCSwitch.class, "equipmentContainer=?", bayId);
    }

    /**
     * 根据bayId 获取隔离开关
     *
     * @param bayId
     * @return
     */
    public List<Disconnector> getDisconnectorsByBayId(String bayId) {
        return dao.findByCondition(Disconnector.class, "equipmentContainer=?", bayId);
    }

    /**
     * 根据bayId 获取
     *
     * @param bayId
     * @return
     */
    public List<EnergyConsumer> getEnergyConsumersByBayId(String bayId) {
        return dao.findByCondition(EnergyConsumer.class, "equipmentContainer=? ", bayId);
    }

    /**
     * 根据bayId 获取发电机组
     *
     * @param bayId
     * @return
     */
    public List<GeneratingUnit> getGeneratingUnitsByBayId(String bayId) {
        return dao.findByCondition(GeneratingUnit.class, "equipmentContainer=? ", bayId);
    }

    /**
     * 根据变电站Id获取发电机组
     *
     * @param stationId
     * @return
     */
    public List<GeneratingUnit> getGeneratingUnitsByStationId(String stationId) {
        return dao.findByCondition(GeneratingUnit.class, "subId=? ", stationId);
    }

    /**
     * 根据变电站Id和发电机组名称获取发电机组
     *
     * @param stationId
     * @param name
     * @return
     */
    public List<GeneratingUnit> getGeneratingUnitsByStationIdAndName(String stationId, String name) {
        return dao.findByCondition(GeneratingUnit.class, "subId=? and name=? ", stationId, name);
    }

    /**
     * 根据bayId 获取
     *
     * @param bayId
     * @return
     */
    public List<Ground> getGroundsByBayId(String bayId) {
        return dao.findByCondition(Ground.class, "equipmentContainer=? ", bayId);
    }

    /**
     * 根据bayId 获取接地刀闸
     *
     * @param bayId
     * @return
     */
    public List<GroundDisconnector> getGroundDisconnectorsByBayId(String bayId) {
        return dao.findByCondition(GroundDisconnector.class, "equipmentContainer=? ", bayId);
    }

    /**
     * 根据bayId 获取发电机组
     *
     * @param bayId
     * @return
     */
    public List<HydroGeneratingUnit> getHydroGeneratingUnitsByBayId(String bayId) {
        return dao.findByCondition(HydroGeneratingUnit.class, "equipmentContainer=? ", bayId);
    }

    /**
     * 变电站Id获取发电机
     *
     * @param stationId
     * @return
     */
    public List<HydroGeneratingUnit> getHydroGeneratingUnitsByStationId(String stationId) {
        return dao.findByCondition(HydroGeneratingUnit.class, "subId=? ", stationId);
    }

    /**
     * 根据变电站Id 和发电机名称获取发电机
     *
     * @param stationId
     * @param name
     * @return
     */
    public List<HydroGeneratingUnit> getHydroGeneratingUnitsByStationIdAndName(String stationId, String name) {
        return dao.findByCondition(HydroGeneratingUnit.class, "subId=? and name=? ", stationId, name);
    }

    /**
     * 根据bayId 获取火电机组
     *
     * @param bayId
     * @return
     */
    public List<ThermalGeneratingUnit> getThermalGeneratingUnitsByBayId(String bayId) {
        return dao.findByCondition(ThermalGeneratingUnit.class, "equipmentContainer=? ", bayId);
    }

    /**
     * 根据变电站Id名称获取火力发电机组
     *
     * @param StationId
     * @return
     */
    public List<ThermalGeneratingUnit> getThermalGeneratingUnitsByStationId(String StationId) {
        return dao.findByCondition(ThermalGeneratingUnit.class, "subId=? ", StationId);
    }

    /**
     * 根据变电站Id和发电机组名称获取火力发电机组
     *
     * @param StationId
     * @param name
     * @return
     */
    public List<ThermalGeneratingUnit> getThermalGeneratingUnitsByStationIdAndName(String StationId, String name) {
        return dao.findByCondition(ThermalGeneratingUnit.class, "subId=? and name=? ", StationId, name);
    }

    /**
     * 根据bayId 获取电机
     *
     * @param bayId
     * @return
     */
    public List<SynchronousMachine> getSynchronousMachinesByBayId(String bayId) {
        return dao.findByCondition(SynchronousMachine.class, "equipmentContainer=? ", bayId);
    }

    /**
     * 根据名称查询变压器
     *
     * @param name
     * @return
     */
    public PowerTransformer getPowerTransformersByStationIdAndPowerName(String stationId, String name) {
        List<PowerTransformer> list = dao.findByCondition(PowerTransformer.class, "subId=? and name=? ", stationId,
                name);
        if (list.size() > 0)
            return list.get(0);
        else
            return null;

    }

    /**
     * 根据名称查询
     *
     * @param name
     * @return
     */
    public List<Compensator> getCompensatorsByName(String name) {
        return dao.findByCondition(Compensator.class, "name=? ", name);
    }

    /**
     * 获取所有变电站
     *
     * @return
     */
    public List<Substation> getAllStations() {
//		return dao.findByCondition(Substation.class, " status=0 ");
        return dao.findAll(Substation.class);
    }

    /**
     * 获取所有线路
     *
     * @return
     */
    public List<ACLineSegment> getAllAclines() {
//		return dao.findByCondition(ACLineSegment.class, " status=0 ");
        return dao.findAll(ACLineSegment.class);
    }

    /**
     * 获取所有断路器
     *
     * @return
     */
    public List<Breaker> getAllBreakers() {
//		return dao.findByCondition(Breaker.class, " status=0 ");
        return dao.findAll(Breaker.class);
    }

    /**
     * 获取所有变压器
     *
     * @return
     */
    public List<PowerTransformer> getAllPowerTransformers() {
//		return dao.findByCondition(PowerTransformer.class, " status=0 ");
        return dao.findAll(PowerTransformer.class);
    }

    /**
     * 获取所有电抗器
     *
     * @return
     */
    public List<Compensator> getAllCompensators() {
//		return dao.findByCondition(Compensator.class, " status=0 ");
        return dao.findAll(Compensator.class);
    }

    /**
     * 获取所有火力 发电机
     *
     * @return
     */
    public List<HydroGeneratingUnit> getAllHydroGeneratingUnits() {
//		return dao.findByCondition(HydroGeneratingUnit.class, " status=0 ");
        return dao.findAll(HydroGeneratingUnit.class);
    }

    /**
     * 获取所有水力 发电机
     *
     * @return
     */
    public List<ThermalGeneratingUnit> getAllThermalGeneratingUnits() {
//		return dao.findByCondition(ThermalGeneratingUnit.class, " status=0 ");
        return dao.findAll(ThermalGeneratingUnit.class);
    }

    /**
     * 获取所有母线
     *
     * @return
     */
    public List<BusbarSection> getAllBusbarSections() {
//		return dao.findByCondition(BusbarSection.class, " status=0 ");
        return dao.findAll(BusbarSection.class);
    }

    /**
     * 根据id获取火力 发电机
     *
     * @return
     */
    public HydroGeneratingUnit getHydroGeneratingUnitById(String id) {
        return dao.findById(id, HydroGeneratingUnit.class);
    }

    /**
     * 根据id获取水力 发电机
     *
     * @return
     */
    public ThermalGeneratingUnit getThermalGeneratingUnitById(String id) {
        return dao.findById(id, ThermalGeneratingUnit.class);
    }

    /**
     * 根据id获取变压器
     *
     * @param name
     * @return
     */
    public PowerTransformer getPowerTransformersById(String id) {
        return dao.findById(id, PowerTransformer.class);
    }

    /**
     * 根据id获取母线
     *
     * @param id
     * @return
     */
    public BusbarSection getBusbarSectionsById(String id) {
        return dao.findById(id, BusbarSection.class);
    }

    /**
     * 根据一次设备ID和类型获取变电站
     *
     * @param type
     * @param equipmentId
     * @return
     */
    public List<Substation> listSubStationsByTypeAndId(String type, String equipmentId) {
        ArrayList<Substation> list = new ArrayList<Substation>();
        if (StringUtils.isNotEmpty(equipmentId)) {
            if ("线路".equals(type)) {
                ACLineSegment acLineSegment = getAcLineSegmentById(equipmentId);
                if (null != acLineSegment) {
                    if (!StringUtils.isEmpty(acLineSegment.getStartST())) {
                        list.add(getStationById(acLineSegment.getStartST()));
                    }
                    if (!StringUtils.isEmpty(acLineSegment.getEndST())) {
                        list.add(getStationById(acLineSegment.getEndST()));
                    }
                } else {
                    DcLinesegment dcLineSegment = getDcLinesegmentById(equipmentId);
                    if (null != dcLineSegment) {
                        if (!StringUtils.isEmpty(dcLineSegment.getStartST())) {
                            list.add(getStationById(dcLineSegment.getStartST()));
                        }
                        if (!StringUtils.isEmpty(dcLineSegment.getEndST())) {
                            list.add(getStationById(dcLineSegment.getEndST()));
                        }
                    }
                }
            } else if ("变压器".equals(type)) {
                PowerTransformer powerTransformer = getPowerTransformersById(equipmentId);
                if (null != powerTransformer && StringUtils.isNotEmpty(powerTransformer.getSubId())) {
                    list.add(getStationById(powerTransformer.getSubId()));
                }
            } else if ("母线".equals(type)) {
                BusbarSection bus = getBusbarSectionsById(equipmentId);
                if (null != bus && StringUtils.isNotEmpty(bus.getSubId())) {
                    list.add(getStationById(bus.getSubId()));
                }
            } else if ("断路器".equals(type)) {
                Breaker breaker = getBreakerByBreakerId(equipmentId);
                if (null != breaker && StringUtils.isNotEmpty(breaker.getSubId())) {
                    list.add(getStationById(breaker.getSubId()));
                }
            } else if ("电抗器".equals(type)) {
                Compensator compensator = getCompensatorById(equipmentId);
                if (null != compensator && StringUtils.isNotEmpty(compensator.getSubId())) {
                    list.add(getStationById(compensator.getSubId()));
                }
            }
        }
        return list;
    }

    /**
     * 获取所有保护设备
     *
     * @return
     */
    public List<ProtectionEquipment> listAllProtectionEquipments() {
        return dao.findAll(ProtectionEquipment.class);
    }

    public List<ProtectionEquipment> listAllProtectionEquipments(int[] range) {
        return dao.findByCondition(null, null, null, range, ProtectionEquipment.class);
    }

    /**
     * count所有保护设备
     */
    public int countAllProtection() {
        return (int) dao.count(ProtectionEquipment.class);
    }

    /**
     * 获取所有主保护设备
     *
     * @return
     */
    public List<ProtectionEquipment> listAllMainProtectionEquipments() {
        return dao.findByCondition(ProtectionEquipment.class, " type like ? ", "%主%");
    }

    public ProtectionEquipment getProtectionEquipmentByPtId(String ptId) {
        List<ProtectionEquipment> list = dao.findByCondition(ProtectionEquipment.class, "ptId=?",
                ptId);
        if (list != null && list.size() > 0) {
            return list.get(0);
        }
        return null;
    }

    public List<Breaker> getBreakersByName(String name) {
        return dao.findByCondition(Breaker.class, "name=?  ", name);
    }

    public List<BusbarSection> getBusbarSectionsByName(String name) {
        return dao.findByCondition(BusbarSection.class, "name=? ", name);
    }

    public List<TransformerWinding> getTransformerWindingsByName(String name) {
        return dao.findByCondition(TransformerWinding.class, "name=? ", name);
    }

    public TransformerWinding getTransformerWindingById(String id) {
        return dao.findById(id, TransformerWinding.class);
    }

    public List<ProtectionEquipment> getProtectionEquipmentsByName(String name) {
        return dao.findByCondition(ProtectionEquipment.class, "name=? ", name);
    }

    public List<ProtectionEquipment> listsByStationIdAndProtectedId(String stationId, String protectedId) {
        return dao.findByCondition(ProtectionEquipment.class, "subId=? and protectedId=? ",
                stationId, protectedId);
    }

    public List<HostControlArea> findAllHostControlArea() {
//		return dao.findByCondition(HostControlArea.class, "status=0");
        return dao.findAll(HostControlArea.class);
    }

    public List<SubControlArea> findsubControlAreasByHostControlArea(String id) {
        return dao.findByCondition(SubControlArea.class, "hostControlArea =? ", id);
    }

    public List<SubControlArea> findsubControlAreasByName(String name) {
        return dao.findByCondition(SubControlArea.class, "name =? ", name);
    }

    /**
     * 通过rdfid获取subControlArea
     *
     * @param rdfid
     * @return
     */
    public SubControlArea findsubControlAreaByRdfid(String rdfid) {
        List<SubControlArea> list = dao.findByCondition(SubControlArea.class, "rdfId =? ", rdfid);
        if (list.size() > 0) {
            return list.get(0);
        }
        return null;
    }

    public List<Substation> findSubstationBySubControlAreaId(String id) {
        return dao.findByCondition(Substation.class, "subControlArea=? ", id);
    }

    public List<Substation> findSubstationByRdfId(String id) {
        return dao.findByCondition(Substation.class, "subControlArea=? ", id);
    }

    /**
     * 获得所有的SubControlArea
     *
     * @return
     */
    public List<SubControlArea> findAllSubControlAreas() {
        return dao.findAll(SubControlArea.class);
    }

    /**
     * 根据变压器rdfId查询电压绕阻
     *
     * @param rdfId
     * @return
     */
    public List<TransformerWinding> getTransformerWindingsBypowerTransformerRdfId(String rdfId) {
        List<TransformerWinding> rtn = new ArrayList<TransformerWinding>();
        if (StringUtils.isEmpty(rdfId)) {
            return rtn;
        }
        rtn = dao.findByCondition(TransformerWinding.class, "powerTransformer=? ", rdfId);
        return rtn;
    }

    /**
     * 根据变压器Id查询电压绕阻
     *
     * @param id
     * @return
     */
    public List<TransformerWinding> getTransformerWindingsBypowerTransformerId(String id) {
        List<TransformerWinding> rtn = new ArrayList<TransformerWinding>();
        PowerTransformer transformer = getPowerTransformersById(id);
        if (transformer == null || StringUtils.isEmpty(transformer.getRdfId())) {
            return rtn;
        }
        rtn = dao.findByCondition(TransformerWinding.class, "powerTransformer=? ", transformer.getRdfId());
        return rtn;
    }

    /**
     * 根据Bay ID 查找线
     *
     * @param id
     * @return
     */
    public List<ACLineSegment> getAcLineSegmentByBayId(String id) {
        return dao.findByCondition(ACLineSegment.class, "equipmentContainer=?", id);
    }
//
//	public void deleteVoltageLevelById(String id) {
//		this.sessionContext.getBusinessObject(CimManager.class).delete(id, VoltageLevel.class);
//	}
//
//	public void deleteBreaker(Breaker breaker) {
//		this.sessionContext.getBusinessObject(CimManager.class).delete(breaker.getId(), Breaker.class);
//	}
//
//	public void deleteSubstation(Substation station) {
//		this.sessionContext.getBusinessObject(CimManager.class).delete(station.getId(), Substation.class);
//	}
//
//	public void deleteBusbar(BusbarSection busbar) {
//		this.sessionContext.getBusinessObject(CimManager.class).delete(busbar.getId(), BusbarSection.class);
//	}
//
//	public VoltageLevel createVoltageLevel(VoltageLevel preVoltageLevel) {
//		return this.sessionContext.getBusinessObject(CimManager.class).createOrUpdate(preVoltageLevel,
//				VoltageLevel.class);
//	}
//
//	public PowerTransformer createPowerTransformer(PowerTransformer prePowerTransformer) {
//		return this.sessionContext.getBusinessObject(CimManager.class).createOrUpdate(prePowerTransformer,
//				PowerTransformer.class);
//	}
//
//	public void deletePowerTransformer(String id) {
//		this.sessionContext.getBusinessObject(CimManager.class).delete(id, PowerTransformer.class);
//	}
//
//	public void updateVoltageLevel(VoltageLevel preVoltageLevel) {
//		this.sessionContext.getBusinessObject(CimManager.class).createOrUpdate(preVoltageLevel, VoltageLevel.class);
//	}
//
//	public void updateACLineSegment(ACLineSegment ac) {
//		this.sessionContext.getBusinessObject(CimManager.class).createOrUpdate(ac, ACLineSegment.class);
//	}
//
//	public ACLineSegment createACLineSegment(ACLineSegment ac) {
//		return this.sessionContext.getBusinessObject(CimManager.class).createOrUpdate(ac, ACLineSegment.class);
//
//	}

    /**
     * 根据线路名称，长度范围查询
     *
     * @param aCLineSegmentName
     * @param aClineSegmentLengthMin
     * @param aClineSegmentLengthMax
     * @return
     */
    public List<ACLineSegment> getAcLineSegmentByNameAndLength(String aCLineSegmentName, Float voltage) {
        String sql = "";
        if (aCLineSegmentName != null && !aCLineSegmentName.isEmpty()) {
            sql += " name like '%" + aCLineSegmentName + "%' ";
        }
        if (voltage != null) {
            if (!StringUtils.isEmpty(sql)) {
                sql += " and ";
            }
            sql += "standVoltagelevel = " + voltage;
        }
        if (StringUtils.isEmpty(sql)) {
            return getAcLineSegmentsBystandVoltagelevel500();
        } else {
            return dao.findByCondition(ACLineSegment.class, sql);
        }
    }

    /**
     * 查询大于500KV的线路
     *
     * @return
     */
    public List<ACLineSegment> getAcLineSegmentsBystandVoltagelevel500() {
        return dao.findByCondition(ACLineSegment.class, "standVoltagelevel> 499 ");
    }

    public List<Breaker> getBreakerBySubNameAndvoltage500() {
        return dao.findByCondition(Breaker.class, " standVoltagelevel>499");
    }

//	/**
//	 * 更新线路
//	 */
//	public ACLineSegment createOrUpdateAcline(ACLineSegment line) {
//		return this.sessionContext.getBusinessObject(CimManager.class).createOrUpdate(line, ACLineSegment.class);
//	}
//
//	/**
//	 * 更新直流线
//	 */
//	public DcLinesegment createOrUpdateDcline(DcLinesegment line) {
//		return this.sessionContext.getBusinessObject(CimManager.class).createOrUpdate(line, DcLinesegment.class);
//	}
//
//	/**
//	 * 更新创建Breaker
//	 *
//	 * @return
//	 */
//	public Breaker createOrUpdateBreaker(Breaker breaker) {
//		return this.sessionContext.getBusinessObject(CimManager.class).createOrUpdate(breaker, Breaker.class);
//	}
//
//	/**
//	 * 更新Substation
//	 */
//	public Substation createOrUpdateStation(Substation station) {
//		return this.sessionContext.getBusinessObject(CimManager.class).createOrUpdate(station, Substation.class);
//	}
//
//	/**
//	 * 更新母线
//	 */
//	public BusbarSection createOrUpdateBusbar(BusbarSection busbar) {
//		return this.sessionContext.getBusinessObject(CimManager.class).createOrUpdate(busbar, BusbarSection.class);
//	}
//
//	public Compensator createOrUpdateCompensator(Compensator com) {
//		return this.sessionContext.getBusinessObject(CimManager.class).createOrUpdate(com, Compensator.class);
//	}
//
//	public PowerTransformer createOrUpdateTransformer(PowerTransformer powerTransformer) {
//		return this.sessionContext.getBusinessObject(CimManager.class).createOrUpdate(powerTransformer,
//				PowerTransformer.class);
//	}
//
//	public void deleteAcLine(ACLineSegment line) {
//		this.sessionContext.getBusinessObject(CimManager.class).delete(line.getId(), ACLineSegment.class);
//	}
//
//	public void deleteDcLine(DcLinesegment line) {
//		this.sessionContext.getBusinessObject(CimManager.class).delete(line.getId(), DcLinesegment.class);
//	}
//
//	public void deleteCompenstor(Compensator com) {
//		this.sessionContext.getBusinessObject(CimManager.class).delete(com.getId(), Compensator.class);
//	}

    /**
     * 根据变电站Id 被保护设备Id 查找被保护设备的主保护
     *
     * @param stationId
     * @param protectedId
     * @return
     */
    public List<ProtectionEquipment> listMainEquipmentsByStationIdAndprotectedId(String stationId, String protectedId) {
        List<ProtectionEquipment> list = dao.findByCondition(ProtectionEquipment.class,
                "subId=? and protectedId=? and type like '%主%' ", stationId, protectedId);
        return list;
    }

    /**
     * 根据 被保护设备Id 查找被保护设备两端站的主保护
     *
     * @param stationId
     * @param protectedId
     * @return
     */
    public List<ProtectionEquipment> listMainEquipmentsByprotectedId(String protectedId) {
        List<ProtectionEquipment> list = dao.findByCondition(ProtectionEquipment.class,
                "protectedId=? and type like '%主%' ", protectedId);
        return list;
    }

    /**
     * 获得变压器保护根据变电站和变压器id
     *
     * @param stationId
     * @param powerId
     * @return
     */
    public List<ProtectionEquipment> listPowerProtectByStationIdAndPowerId(String stationId, String powerId) {
        List<ProtectionEquipment> list = dao.findByCondition(ProtectionEquipment.class,
                "subId=? and protectedId=? and (type like '%主%' or  type like'%非电量%' or type like'%失灵%')",
                stationId, powerId);
        return list;
    }

    /**
     * 根据各种条件查询保护设备
     *
     * @param substationName
     * @param name
     * @param privateName
     * @param withOutSubstation
     * @param withOutPrim
     * @param selectedVoltage
     * @param range
     * @return List<ProtectionEquipment>
     */
    public List<ProtectionEquipment> getProtectionEquipmentBySubstationName(String substationName, String name,
                                                                            String privateName, boolean withOutSubstation, boolean withOutPrim, int selectedVoltage, int[] range) {
        String whereCase = "1=1  ";
        List<Object> args = new ArrayList<Object>();
        if (StringUtils.isNotEmpty(substationName)) {
            whereCase += " and subName like ?";
            args.add("%" + substationName + "%");
        }
        if (StringUtils.isNotEmpty(privateName)) {
            whereCase += " and privateStationName like ?";
            args.add("%" + privateName + "%");
        }
        if (StringUtils.isNotEmpty(name)) {
            whereCase += " and name like ?";
            args.add("%" + name + "%");
        }
        if (withOutSubstation) {
            whereCase += " and subId is null";
        }
        if (withOutPrim) {
            whereCase += " and protectedId is null";
        }
        if (selectedVoltage != 0) {
            whereCase += " and standvoltage = ?";
            args.add(selectedVoltage);
        }
        return dao.findByCondition(whereCase, args.toArray(), null, range, ProtectionEquipment.class);
    }

    /**
     * 根据各种条件查询保护设备条数
     *
     * @param substationName
     * @param name
     * @param privateName
     * @param withOutSubstation
     * @param withOutPrim
     * @param selectedVoltage
     * @return 条数（int）
     */
    public int countEquipmentBySubstationName(String substationName, String name, String privateName,
                                              boolean withOutSubstation, boolean withOutPrim, int selectedVoltage) {
        String whereCase = "1=1  ";
        List<Object> args = new ArrayList<Object>();
        if (StringUtils.isNotEmpty(substationName)) {
            whereCase += " and subName like ?";
            args.add("%" + substationName + "%");
        }
        if (StringUtils.isNotEmpty(privateName)) {
            whereCase += " and privateStationName like ?";
            args.add("%" + privateName + "%");
        }
        if (StringUtils.isNotEmpty(name)) {
            whereCase += " and name like ?";
            args.add("%" + name + "%");
        }
        if (withOutSubstation) {
            whereCase += " and subId is null";
        }
        if (withOutPrim) {
            whereCase += " and protectedId is null";
        }
        if (selectedVoltage != 0) {
            whereCase += " and standvoltage = ?";
            args.add(selectedVoltage);
        }
        return (int) dao.count(whereCase, args.toArray(), ProtectionEquipment.class);
    }

    /**
     * 返回当前一次设备的类型（中文描述）
     *
     * @param obj
     * @return
     */
    public String getEquipmentType(Object object) {
        if (object instanceof ACLineSegment) {
            return "线路";
        } else if (object instanceof BusbarSection) {
            return "母线";
        } else if (object instanceof Breaker) {
            return "断路器";
        } else if (object instanceof PowerTransformer) {
            return "变压器";
        } else if (object instanceof Compensator) {
            return "电容器";
        } else if (object instanceof TransformerWinding) {
            return "变压器绕组";
        }
        return "未知";
    }

    /**
     * 根据保护Id 获取保护设备
     *
     * @param id
     * @return
     */
    public ProtectionEquipment getProtectionEquipmentById(String id) {
        return dao.findById(id, ProtectionEquipment.class);
    }

    /**
     * 根据Id的集合查询数据
     *
     * @param ids
     * @return
     */
    public List<ProtectionEquipment> getProtectionEquipmentsByIds(String[] ids) {
        return dao.findByConditionIN("id", ids, ProtectionEquipment.class);
    }

    /**
     * 根据名字获取最符合名称的线路
     *
     * @param name
     * @param list
     * @return
     */
    public ACLineSegment getACLineSegmentByName(String name, Collection<ACLineSegment> list) {
        if (StringUtils.isEmpty(name)) {
            return null;
        }
        ACLineSegment rtn = null;
        if (null == list) {
            list = getAcLineSegmentsBystandVoltagelevel500();
        }
        for (ACLineSegment acline : list) {
            if (CimUtils.lineAbsoluteNameMatching(name, acline.getName())) {
                rtn = acline;
                break;
            }
        }
        if (null == rtn) {
            for (ACLineSegment acline : list) {
                if (CimUtils.lineNameMatching(name, acline.getName(), false)) {
                    rtn = acline;
                    break;
                }
            }
        }
        return rtn;
    }

    /**
     * 根据名字获取最符合名称的线路
     *
     * @param name
     * @param list
     * @return LineSegment
     */
    public LineSegment getLineSegmentByName(String name, Collection<LineSegment> list) {
        if (StringUtils.isEmpty(name)) {
            return null;
        }
        LineSegment rtn = null;
        if (null == list) {
            return null;
        }
        for (LineSegment acline : list) {
            if (CimUtils.lineAbsoluteNameMatching(name, acline.getName())) {
                rtn = acline;
                break;
            }
        }
        if (null == rtn) {
            for (LineSegment acline : list) {
                if (CimUtils.lineNameMatching(name, acline.getName(), false)) {
                    rtn = acline;
                    break;
                }
            }
        }
        return rtn;
    }

    /**
     * 根据名字获取最符合名称的直流线路
     *
     * @param name
     * @param list
     * @return
     */
    public DcLinesegment getDcLineSegmentByName(String name, Collection<DcLinesegment> list) {
        if (StringUtils.isEmpty(name)) {
            return null;
        }
        DcLinesegment rtn = null;
        if (null == list) {
            list = findAllDclineSegement();
        }
        for (DcLinesegment acline : list) {
            if (CimUtils.lineAbsoluteNameMatching(name, acline.getName())) {
                rtn = acline;
                break;
            }
        }
        if (null == rtn) {
            for (DcLinesegment acline : list) {
                if (CimUtils.dclineNameMatching(name, acline.getName())) {
                    rtn = acline;
                    break;
                }
            }
        }
        return rtn;
    }

    /**
     * 全部可用不可用数据
     *
     * @return
     */
    public List<BaseVoltage> findAllBaseVoltages() {
        return dao.findAll(BaseVoltage.class);
    }

    /**
     * 获取所有可用BaseVoltage
     *
     * @return
     */
    public List<BaseVoltage> findAllBaseVoltage() {
//		return dao.findByCondition(BaseVoltage.class, "status=?", 0);
        return dao.findAll(BaseVoltage.class);
    }

    /**
     * 获取所有可用BaseVoltage并排序
     *
     * @return
     */
    public List<BaseVoltage> findAllBaseVoltageOrder() {
        return dao.findByCondition(BaseVoltage.class, "order by nominalVoltage desc");
    }

    public BaseVoltage findBaseVoltageByStandVoltage(Float vol) {
        String v = vol.toString();
        if (v.endsWith(".0")) {
            v = String.valueOf(vol.intValue());
        }
        BaseVoltage baseVoltage = null;
        List<BaseVoltage> bases = dao.findByCondition(BaseVoltage.class, "name like ?", v + "%");
        if (bases.size() > 0) {
            baseVoltage = bases.get(0);
        }
        return baseVoltage;
    }

    /**
     * 通过制定条件、参数查找一次设备
     *
     * @return
     */
    public <T> List<T> findPrimaryDeviceByCondication(String sql, Object[] args, Class<T> t) {
        return dao.findByCondition(t, sql, args);
    }

    /**
     * 直流线
     *
     * @param standVoltagelevel
     * @return
     */
    public List<DcLinesegment> getDcLineSegmentsByStandVoltagelevel(float standVoltagelevel) {
        return dao.findByCondition(DcLinesegment.class, "standVoltagelevel>=? ", standVoltagelevel);
    }

    public List<Float> listAllDcLineVoltage() {
        List<DcLinesegment> voltages = dao.findByCondition(DcLinesegment.class,
                "1=1 group by standVoltagelevel order by standVoltagelevel desc");
        List<Float> result = new ArrayList<>();
        for (DcLinesegment v : voltages) {
            result.add(v.getStandVoltagelevel());
        }
        return result;
    }

    public DcLinesegment getDcLinesegmentById(String id) {
        if (StringUtils.isEmpty(id)) {
            return null;
        }
        return dao.findById(id, DcLinesegment.class);
    }

    public LineSegment getLineSegmentById(String id) {
        ACLineSegment ac = getAcLineSegmentById(id);
        if (ac != null) {
            return ac;
        } else {
            return getDcLinesegmentById(id);
        }
    }
    
    public LineSegmentHistory getHistoryLineSegmentById(String id) {
        List<ACLineSegmentHistory> ac = dao.findByCondition(ACLineSegmentHistory.class, " cimId = ?1 ", id);
        if (ac.size()>0 ) {
            return ac.get(0);
        } else {
        	List<DcLinesegmentHistory> dc = dao.findByCondition(DcLinesegmentHistory.class, " cimId = ?1 ", id);
        	 if (dc.size()>0 ) {
                 return dc.get(0);
             } 
        }
		return null;
    }
    

    public List<LineSegment> findAllLineSegments() {
        List<LineSegment> lines = new ArrayList<>();
        lines.addAll(findAllAcLineSegement());
        lines.addAll(findAllDclineSegement());
        return lines;
    }

    /**
     * 获取名字最接近的变电站
     *
     * @param name
     * @param list
     * @return
     */
    public Substation getSubstationByName(String name, Collection<Substation> list) {
        if (StringUtils.isEmpty(name)) {
            return null;
        }
        if (null == list) {
            list = getAllStations();
        }
        Substation rtn = null;
        for (Substation station : list) {
            if (StringUtils.isNotEmpty(station.getName()) && name.equals(station.getName())) {
                rtn = station;
                break;
            }
        }
        if (null == rtn) {
            for (Substation station : list) {
                if (CimUtils.stationNameMatching(name, station.getName())) {
                    rtn = station;
                    break;
                }
            }
        }
        if (null == rtn) {
            for (Substation station : list) {
                if (CimUtils.stationNameMatching(name, station.getName(), true)) {
                    rtn = station;
                    break;
                }
            }
        }
        return rtn;
    }

    /**
     * 通过变电站Id 获取交流线段
     *
     * @param stationId
     * @return
     */
    public List<DcLinesegment> getDcLineSegmentsBySubstation(String stationId) {
        return dao.findByCondition(DcLinesegment.class, "( startST=? or endST=? )  ", stationId, stationId);
    }

    /**
     * 更新 抽出此类是为了方便拦截
     *
     * @param bean
     * @param T
     * @return
     */
    @Interceptors({CimModeCreateOrUpdatelInterceptor.class})
    public <T> T createOrUpdate(T bean, Class<T> T) {
        return dao.createOrUpdate(bean, T);
    }

    /**
     * 删除 抽出此类是为了方便拦截
     *
     * @param bean
     * @param T
     * @return
     */
    @Interceptors({CimModeDeleteInterceptor.class})
    public <T> void delete(Object id, Class<T> T) {
        dao.delete(id, T);
    }

    /**
     * 通过电压等级获取 stationList
     *
     * @param v1 包括
     * @param v2 不包括
     * @return
     */
    public List<Substation> getStationsByVoltage(Integer v1, Integer v2) {
        List<Substation> list = new ArrayList<>();
        List<Substation> all = dao.findAll(Substation.class);

        for (Substation en : all) {
            float v = en.getStandVoltagelevel();
            if (isInVoltage(v1, v2, v)) {
                list.add(en);
            }
        }
        return list;
    }

    private boolean isInVoltage(Integer v1, Integer v2, float v) {
        return (v1 == null || v >= v1) && (v2 == null || v < v2);
    }

    public List<Substation> getS500List() {
        return getStationsByVoltage(500, null);
    }

    public List<Substation> getS220List() {
        return getStationsByVoltage(220, 500);
    }


    public List<Substation> getS800List() {
        return getStationsByVoltage(800, null);
    }

    /**
     * 获取year=now()的substationId；
     *
     * @return
     */
    public List<String> getSpecialStationIds() {
        ArrayList<String> maintenanceStations = new ArrayList<>();
        List<MaintenanceStation> stations = dao.findByCondition(MaintenanceStation.class, " year=YEAR(now()) group by subStationId");
        for (MaintenanceStation s : stations) {
            maintenanceStations.add(s.getSubStationId());
        }
        return maintenanceStations;
    }

    public HashMap<String, ACLineSegment> getAcLineIdMapByVoltage(Integer v1, Integer v2) {
        HashMap<String, ACLineSegment> map = new HashMap<>();
        for (ACLineSegment en : dao.findAll(ACLineSegment.class)) {
            float v = en.getStandVoltagelevel();
            if (isInVoltage(v1, v2, v)) {
                map.put(en.getId(), en);
            }
        }
        return map;
    }

    /**
     * 获取所有的acLineSegmentList+dcLinesegmentList
     * @return
     */
    public Collection<LineSegment> getAllLineSegmentList() {
        ArrayList<LineSegment> resultList = new ArrayList<>();
        List<ACLineSegment> acLineSegmentList = dao.findAll(ACLineSegment.class);
        List<DcLinesegment> dcLinesegmentList = dao.findAll(DcLinesegment.class);
        resultList.addAll(acLineSegmentList);
        resultList.addAll(dcLinesegmentList);
        return resultList;
    }


}
